package com.ruoyi.web.controller.ksdH5;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileUploadException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.system.domain.HatchetMerchant;

import net.sf.json.JSONObject;

import com.ruoyi.common.utils.Constans;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;

/**
 * H5项目登陆
 * 
 * @author ruoyi
 * @date 2019-06-27
 */
@Controller		 
@RequestMapping("/h5")
public class KsdH5LoginController 
{
	
	    
	 /**
	  * 发送验证码
	  * @param request
	  * @param resp
	  * @return
	  */
 		@RequestMapping("/sendCode")
 		@ResponseBody
 		public Map<String, Object> sendShortMessage(HttpServletRequest request, HttpServletResponse resp) {
 			String head ="v="+Constans.KSD_APP_H5_VERSION;
 			String params ="phone="+request.getParameter("phone")+"&"
 							+"type="+request.getParameter("type"); //1。发送注册的验证码 2.发送忘记密码的验证码
 			String result = HttpUtils.sendPost(Constans.KSD_APP_H5_URL+"/m/sendSMSReg", params,head);
 			return Ksdh5Util.getMap(result);
 		}

	/**
	  * 发送修改密码验证码 和交易密码
	  * @param request
	  * @param resp
	  * @return
	  */
 		@RequestMapping("/sendSMS")
 		@ResponseBody
 		public Map<String, Object> sendSMS(HttpServletRequest request, HttpServletResponse resp) {
 			String head ="v="+Constans.KSD_APP_H5_VERSION+","
 						+"token="+Ksdh5Util.getToken(request, resp);
 			String params ="phone="+request.getParameter("phone");
 			String result = HttpUtils.sendPost(Constans.KSD_APP_H5_URL+"/m/sendSMS", params,head);
 			return Ksdh5Util.getMap(result);
 		}
 		
 		

    /**
     * 卡时代H5用户注册
     * @param request
     * @param response
     * @return
     */
     @RequestMapping("/register")
     @ResponseBody
     public Map<String, Object> h5Register(HttpServletRequest request ,HttpServletResponse response)
     {
    	String phone = request.getParameter("phone");
    	String passwd = request.getParameter("password");
    	passwd =  Ksdh5Util.md5Str(passwd);//加密
    	String parentPhone = request.getParameter("parentPhone");
    	String validate = request.getParameter("validate");
    	String head ="v="+Constans.KSD_APP_H5_VERSION;
    	String params ="phone="+phone+"&" //手机
						+"passwd="+passwd+"&" //密码
						+"parentPhone="+parentPhone+"&"//推荐人手机号
						+"from="+"h5"+"&"//来源
						+"validate="+validate ; //验证码
    	String result = HttpUtils.sendPost(Constans.KSD_APP_H5_URL+"/m/register", params,head);
		return Ksdh5Util.getMap(result);
     }
     
     
     
     /**
      * 忘记密码
      * @param request
      * @param response
      * @return
      */
      @PostMapping("/forgetPwd")
      @ResponseBody
      public Map<String, Object> forgetPwd(HttpServletRequest request ,HttpServletResponse response)
      {
     	String phone = request.getParameter("phone");
     	String newPasswd = request.getParameter("newPasswd");
     	newPasswd =  Ksdh5Util.md5Str(newPasswd);//加密
     	String validate = request.getParameter("validate");
     	String head ="v="+Constans.KSD_APP_H5_VERSION;
     	String params ="phone="+phone+"&" //手机
 						+"newPasswd="+newPasswd+"&" //密码
 						+"validate="+validate;
     	String result = HttpUtils.sendPost(Constans.KSD_APP_H5_URL+"/m/forgetPasswd", params,head);
 		return Ksdh5Util.getMap(result);
      }
     
     /**
	    * 卡时代H5跳转登陆页面
	    * @param request
	    * @param response
	    * @return
	    */
	    
	    @GetMapping("/login")
	    public String ksdH5Login(HttpServletRequest request, HttpServletResponse response)
	    {
	    	return Constans.KSD_APP_H5_LOGIN_URL;
	    }
	    
	    /**
		    * 服务条款
		    * @param request
		    * @param response
		    * @return
		    */
		    
		    @GetMapping("/termsService")
		    public String toTermsServicePage(HttpServletRequest request, HttpServletResponse response)
		    {
		    	return "h5/termsService";
		    }
     
    /**
	    * 安全退出
	    * @param request
	    * @param response
	    * @return
	    */
	    
	    @GetMapping("/logout")
	    public String logout(HttpServletRequest request, HttpServletResponse response)
	    {
	    	//m/exitLanding
	    	String head ="v="+Constans.KSD_APP_H5_VERSION+","
					+ "token="+Ksdh5Util.getToken(request, response);
			String params ="" ;//文件地址
			HttpUtils.sendPost(Constans.KSD_APP_H5_URL+"/m/exitLanding", params,head);
	    	return Constans.KSD_APP_H5_LOGIN_URL;
	    }
	    
	 /**
	  * 登陆操作
	  * @param username
	  * @param password
	  * @return
	  */
    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> ksdH5AjaxLogin(HttpServletRequest request,HttpServletResponse response)
    {	
    	Map<String, Object> map = new HashMap<>();
    	HttpSession session = request.getSession();
    	session.removeAttribute("token");
    	session.removeAttribute("merchant"); //用户信息
    	String head ="v="+Constans.KSD_APP_H5_VERSION;
    	String parameter = request.getParameter("password");
    	String md5Pwd = Ksdh5Util.md5Str(parameter);//加密
    	String params ="phone="+request.getParameter("phone")+"&" //手机
						+"passwd="+md5Pwd; //密码
    	String result = HttpUtils.sendPost(Constans.KSD_APP_H5_URL+"/m/login", params,head);
    	Map<String, Object> map2 = Ksdh5Util.getMap(result);
    	if ("Fail".equals(map2.get("status"))) {
			return map2;
		}
    	
		JSONObject jsonObject = JSONObject.fromObject(result);
		if ("200".equals(jsonObject.get("apistatus").toString()) && StringUtils.isEmpty(jsonObject.get("error").toString())) {
			//登陆成功
			String  merStr = jsonObject.get("merchant").toString();
			HatchetMerchant merchant = JSON.parseObject(merStr, HatchetMerchant.class);
			session.setMaxInactiveInterval(60*30);//session过期时间 30分钟
			session.setAttribute("merchant", merchant); //用户信息、
			session.setAttribute("token", jsonObject.get("token"));//token
			session.setAttribute("userStatus", jsonObject.get("userStatus"));//用户状态
			session.setAttribute("DebitCardNum", jsonObject.get("DebitCardNum"));//储蓄卡
			session.setAttribute("CreditCardNum", jsonObject.get("CreditCardNum"));//信用卡
			session.setAttribute("transPWStatus", jsonObject.get("transPWStatus"));
			map.put("status", BusinessStatus.SUCCESS);
			map.put("msg", jsonObject.get("apimsg"));
		}else {
			map.put("status", BusinessStatus.FAIL);
			map.put("msg", jsonObject.get("error"));
		}
    	return map;
    }
	 
	/**
	  * 跳转首页
	  * @param request
	  * @param response
	  * @return
	  */
   @GetMapping("/index")
   public String index(HttpServletRequest request,HttpServletResponse response)
   {	
	boolean checkSession = Ksdh5Util.checkSession(request, response);
	if (checkSession) {
		return "h5/index";
	} else {
		return Constans.KSD_APP_H5_LOGIN_URL;
	}
	
   } 
   
  
 /**
  * 查看用户信息
  * @param request
  * @param response
  * @return
  */
 @PostMapping("/merInfo")
 @ResponseBody
 public Map<String, Object> merInfo(HttpServletRequest request,HttpServletResponse response)
 {	
	Map<String, Object> map = new HashMap<>();
	HttpSession session = request.getSession();
	Object merchant = session.getAttribute("merchant");
	Object token = session.getAttribute("token");
	//判断没有登陆状态
	if (StringUtils.isNull(merchant)|| StringUtils.isNull(token)) {
		map.put("status", "out");
	}else {
		map.put("status", BusinessStatus.SUCCESS);
		map.put("merchant", merchant);
		//请求获取我的信息
		String head ="v="+Constans.KSD_APP_H5_VERSION+","
				+ "token="+Ksdh5Util.getToken(request, response);
		String params="";
		String result = HttpUtils.sendGet(Constans.KSD_APP_H5_URL+"/main/mineData", params,head);
		Map<String, Object> map2 = Ksdh5Util.getMap(result);
		if (BusinessStatus.SUCCESS.equals(map2.get("status"))) {
			//用户头像
			Map<String , Object> map3 = JSON.parseObject(result);
			map.put("headImg", map3.get("userImg"));
		}
		
	}
	
	return map;
 } 
 
 
 
 /**
 * 跳转实名认证页面
 * @param request
 * @param response
 * @return
 */
@GetMapping("/realName")
public String realName(HttpServletRequest request,HttpServletResponse response)
{	
	boolean checkSession = Ksdh5Util.checkSession(request, response);
	//判断没有登陆状态
	if (!checkSession) {
		return Constans.KSD_APP_H5_LOGIN_URL;
	}
	return "h5/realName/realName";
} 
 

/**
 * 上传身份证
 * @throws IOException 
 * @throws FileUploadException 
 */
@PostMapping("/uploadIdCard")
@ResponseBody
public Map<String,Object> uploadIdCard(@RequestParam("file") MultipartFile multipartFile,HttpServletRequest request,HttpServletResponse response) throws FileUploadException, IOException {
	Map<String,Object> map = new HashMap<>();
	boolean checkSession = Ksdh5Util.checkSession(request, response);
	//判断没有登陆状态
	if (!checkSession) {
		map.put("status","out");
		return map;
	}
	String imageType = request.getParameter("imageType"); //身份正图片类型 10E正面 10F反面  
	String ocrType = request.getParameter("ocrType"); //0正面 1反面
	HttpSession session = request.getSession();
	HatchetMerchant merchant = (HatchetMerchant)session.getAttribute("merchant");
	map = Ksdh5Util.imgFile(merchant.getMerchantNo(), multipartFile, imageType,ocrType);
	//调用post请求 app接口
	if (BusinessStatus.SUCCESS.equals(map.get("status"))) {
		String head ="v="+Constans.KSD_APP_H5_VERSION+","
				+ "token="+Ksdh5Util.getToken(request, response);
		String url = map.get("url").toString();
		String params ="imgUrl="+URLEncoder.encode(url,"utf-8")+"&" //文件地址
						+"imageType="+request.getParameter("imageType")+"&" //图片类型
						+"ocrType="+request.getParameter("ocrType")+"&" //身份证 正反  0 正面  1反面
						+"num="+request.getParameter("num"); //身份证上传次数
			String result = HttpUtils.sendPost(Constans.KSD_APP_H5_URL+"/f/H5imgFile", params,head);
			map = Ksdh5Util.getMap(result);
			map.put("obj", JSON.parse(result));
	}
	return map;
}
 
/**
 * 提交实名认证
 * @throws IOException 
 * @throws FileUploadException 
 */
@PostMapping("/submitReal")
@ResponseBody
public Map<String,Object> submitReal(HttpServletRequest request,HttpServletResponse response) throws FileUploadException, IOException {
	Map<String,Object> map = new HashMap<>();
	boolean checkSession = Ksdh5Util.checkSession(request, response);
	//判断没有登陆状态
	if (!checkSession) {
		map.put("status","out");
		return map;
	}
	//调用post请求 app接口
	String head ="v="+Constans.KSD_APP_H5_VERSION+","
				+"token="+Ksdh5Util.getToken(request, response);
	String name = request.getParameter("name");
	String encode = URLEncoder.encode(name);//解决中文乱码
	String idcard = request.getParameter("idcard");
	String params ="name="+encode+"&"
					+"idcard="+idcard;
	String result = HttpUtils.sendPost(Constans.KSD_APP_H5_URL+"/m/authenticate", params,head);
	map = Ksdh5Util.getMap(result);
	return map;
}
 
/**
 * 跳转设置列表页面
 * @param request
 * @param response
 * @return
 */
@GetMapping("/setUp")
public String toSetUpPage(HttpServletRequest request,HttpServletResponse response)
{	
	boolean checkSession = Ksdh5Util.checkSession(request, response);
	//判断没有登陆状态
	if (!checkSession) {
		return Constans.KSD_APP_H5_LOGIN_URL;
	}
	return "h5/setUp/setUpList";
} 

/**
 * 跳转隐私协议页面
 * @param request
 * @param response
 * @return
 */
@GetMapping("/privateAgreement")
public String toPrivateAgreementPage(HttpServletRequest request,HttpServletResponse response,ModelMap map)
{	
	boolean checkSession = Ksdh5Util.checkSession(request, response);
	//判断没有登陆状态
	if (!checkSession) {
		return Constans.KSD_APP_H5_LOGIN_URL;
	}
	return "h5/setUp/privateAgreement";
} 

/**
 * 跳转修改登陆密码页面
 * @param request
 * @param response
 * @return
 */
@GetMapping("/changeLoginPassword")
public String toChangeLoginPasswordPage(HttpServletRequest request,HttpServletResponse response,ModelMap map)
{	
	boolean checkSession = Ksdh5Util.checkSession(request, response);
	//判断没有登陆状态
	if (!checkSession) {
		return Constans.KSD_APP_H5_LOGIN_URL;
	}
	HatchetMerchant merchant = Ksdh5Util.getMerchant(request, response);
	map.addAttribute("phone", merchant.getPHONE());
	return "h5/setUp/changeLoginPassword";
} 



/**
 * 跳转修改交易密码页面
 * @param request	
 * @param response
 * @return
 */
@GetMapping("/changeTradPassword")
public String toChangeTradingPasswordPage(HttpServletRequest request,HttpServletResponse response,ModelMap map)
{	
	boolean checkSession = Ksdh5Util.checkSession(request, response);
	//判断没有登陆状态
	if (!checkSession) {
		return Constans.KSD_APP_H5_LOGIN_URL;
	}
	HatchetMerchant merchant = Ksdh5Util.getMerchant(request, response);
	map.addAttribute("phone", merchant.getPHONE());
	return "h5/setUp/changeTradingPassword";
} 

//

/**
 *修改登陆密码
 * @throws IOException 
 * @throws FileUploadException 
 */
@PostMapping("/updateLoginPwd")
@ResponseBody
public Map<String,Object> updateLoginPwd(HttpServletRequest request,HttpServletResponse response) throws FileUploadException, IOException {
	Map<String,Object> map = new HashMap<>();
	boolean checkSession = Ksdh5Util.checkSession(request, response);
	//判断没有登陆状态
	if (!checkSession) {
		map.put("status","out");
		return map;
	}
	//调用post请求 app接口
	String head ="v="+Constans.KSD_APP_H5_VERSION+","
				+"token="+Ksdh5Util.getToken(request, response);
	System.out.println(Ksdh5Util.getToken(request, response));
	String newPasswd = request.getParameter("newPasswd");
	String oldPasswd =request.getParameter("oldPasswd");
	newPasswd =  Ksdh5Util.md5Str(newPasswd);//加密
	oldPasswd =  Ksdh5Util.md5Str(oldPasswd);//加密
	String params ="newPasswd="+newPasswd+"&"
			       +"oldPasswd="+oldPasswd;
	String result = HttpUtils.sendPost(Constans.KSD_APP_H5_URL+"/m/modifyPW", params,head);
	map = Ksdh5Util.getMap(result);
	return map;
}

/**
 * 添加/修改交易密码
 * @throws IOException 
 * @throws FileUploadException 
 */
@PostMapping("/resetTransactionPW")
@ResponseBody
public Map<String,Object> resetTransactionPW(HttpServletRequest request,HttpServletResponse response) throws FileUploadException, IOException {
	Map<String,Object> map = new HashMap<>();
	boolean checkSession = Ksdh5Util.checkSession(request, response);
	//判断没有登陆状态
	if (!checkSession) {
		map.put("status","out");
		return map;
	}
	//调用post请求 app接口
	String head ="v="+Constans.KSD_APP_H5_VERSION+","
				+"token="+Ksdh5Util.getToken(request, response);
	String transPW = request.getParameter("transPW");
	String phone =request.getParameter("phone");
	String validate = request.getParameter("validate");
	transPW =  Ksdh5Util.md5Str(transPW);//加密
	String params ="transPW="+transPW+"&"
			       +"phone="+phone+"&"
					+"validate="+validate;
	String result = HttpUtils.sendPost(Constans.KSD_APP_H5_URL+"/m/resetTransactionPW", params,head);
	map = Ksdh5Util.getMap(result);
	return map;
}


}